<?php


namespace Gateway;


class GatewayResponse
{
    /**
     * 协议版本
     */
    public $ver;
    /**
     * 响应状态码
     */
    public $code;
    /**
     * 结果描述
     */
    public $msg;
    /**
     *
     */
    public $gwRequestID;
    /**
     * 业务action
     */
    public $act;
    /**
     * 响应时间戳
     */
    public $timestamp;
    /**
     * 业务响应数据
     */
    public $bizContent;
    /**
     * 签名数据
     */
    public $sign;
    /**
     * 签名类型
     */
    public $signType;
    /**
     * 验签结果
     */
    public $signVerifyResult;

    public function __construct()
    {
    }

    public function initWithCode($code, $msg) {
        $this->code = $code;
        $this->msg = $msg;
        if ("-1" == $code) {
            LOG::ERROR("本地执行发生异常 : ".$msg);
        }
    }

    /**
     * 把对象序列化为JSON字符串
     * @return false|string
     */
    public function toJsonStr() {
        $jsonStr = json_encode($this);

        return $jsonStr;
    }

    /**
     * 把json字符串序列化为对象
     * @param $jsonStr
     * @return GatewayResponse
     */
    public static function fromJsonStr($jsonStr) {
        $self = new GatewayResponse();
        $jsonObj = json_decode($jsonStr);
        foreach ($jsonObj as $key => $val) {
            if(property_exists($self,$key)){
                $self->$key = $jsonObj->$key;
            } else {
                Log::WARN("属性未被处理：".$key);
            }
        }

        return $self;
    }

    /**
     * 对返回的数据进行验签
     * @param $key
     * @return mixed
     */
    public function verifySign($key) {
        $result = false;
        do {
            switch($this->signType){
                case "1":{// ECC256
                    break;
                }
                case "2":{//RSA2048
                    break;
                }
                case "3":{// MD5
                    $builder = $this->act;
                    $builder .= "&";
                    $builder .= $this->timestamp;
                    $builder .= "&";
                    $builder .= $this->code;
                    if(!empty($this->bizContent)){
                       $builder .= "&";
                       $builder .= $this->bizContent;
                    }
                    $builder .= "&";
                    $builder .= $key;
                    $signedData = $builder;
                    LOG::DEBUG("验签数据 ：".$signedData);
                    $signBuff = md5($signedData,true);
                    $signHexLowerCase = strtolower(bin2hex($signBuff));
                    if($signHexLowerCase==strtolower($this->sign)){
                        $result = true;
                    }
                    break;
                }
                default : {
                    LOG::ERROR("不支持验签类型 ：".$this->signType);
                    break;
                }
            }



        } while (false);

        return $result;
    }
}
